/**
*结算中心:收件人信息->配送方式->支付方式->优惠券->统计各模块js
*2013-12-07
*/
define(function(require){
	var $=require("jq");
	var Dialog=require("pz_use_dialog.js");
	
	var tips = $('#tips').val();
	if(tips != null && tips.length > 0){
		var tips=new PZ_Dialog({
			  type:["tips"],
			  height:45,
			  width:550,
			  text:tips,
			  buttonCancelText:"知道了", 
			  mask:0.8,
			  isDrag:true ,               //开起拖动
			  delay:5,              //小提示窗口延时几秒关闭 
		});
	}
	
	/**
	*收件人信息
	*/
	function ShouJianRen(ShouJianRenBox){
		var _this_=this;
		//标记是否完全没有地址的用户
		this.isFirst = false;
		//保存收件人区域
		this.shoujianrenBox=ShouJianRenBox;
		//保存默认的地址信息
		this.defaultAddress=$("#sureAddress",this.shoujianrenBox);
		//保存确认收货地址按钮
		this.sureAddressBtn=$(".sure-address-button",this.shoujianrenBox);
		this.sureAddressBtn.click(function(){
			if(_this_.addressListBox.find("li:not(#use-new-address)").size()!=0){
				_this_.modCloseBtn.click();
				$(this).hide();
				/*-----打开配送方式------*/
				if($("#J_ShippingMethod span").attr("ismodstate")!="yes"){
					$("#J_ShippingMethod span").click();
				};
			}else{
				new Dialog({
						  type:"alert",
						  text:"提示信息",
						  tipsText:"收货地址不能为空",
						  buttonSureText:"添加地址", 
						  callBack:function(){         //回调函数
						  		var r=_this_.addressListBox.find("li#use-new-address input").click();
								_this_.changeAddressListSelect(r);
								//return true;             //当回调函数返回值为true的时候，阻止关闭窗口，当有一个可以关闭的状态时，手动调用new出来的对象的closeDialog()方法
						  },
						  mask:0.3,
						  isDrag:true
						  });
			};
		});
		//保存地址列表
		this.addressListBox=$(".address-list",this.shoujianrenBox);
		//防止新添加的未绑定事件
		this.addressListBox.click(function(e){

			var target=e.target;
			//radio按钮
			if(target.tagName=="INPUT"){
				_this_.changeAddressListSelect(target);
			};
			//编辑按钮
			if($(target).attr("class")=="modify-btn"){
				var thisAddressId=$(target).attr("data-address-id");
				_this_.getCurrentAddressText(target);
				//就把所有编辑框设置为可保存
				_this_.setEditSaveState(target);
				_this_.showEditBox();
				_this_.shoujianrenBox.find(".validate-tips").hide();
				/****************/
				_this_.sureAddressBtn.hide();
			};
			//删除按钮
			if($(target).attr("class")=="del-btn"){
				var thisAddressId=$(target).attr("data-address-id");
				_this_.delAddress(target,thisAddressId);
			};
		});
		
		//保存修/关闭按钮
		this.modCloseBtn=$(".colunm-hd span",this.shoujianrenBox);
		this.modCloseBtn.click(function(){
			//如果不是修改状态
			if($(this).attr("ismodstate")!="yes"){
				$(this).text("[关闭]").attr("isModState","yes");
				//显示修改状态
				_this_.showEditBox()
			}else if($(this).attr("ismodstate")!="no"){
				var arr=[];
				if(_this_.userNameInput.attr("issaved")=="yes"){
					arr.push(_this_.userNameInput.val());
				}else{
					_this_.tips(_this_.userNameInput,"用户名不对！",false);
					return false;
				};
				if(_this_.provinceSelect.attr("issaved")=="yes"){
					arr.push(_this_.getSelectedText(_this_.provinceSelect));
				}else{
					_this_.tips(_this_.provinceSelect,"没有选择省份！",false);
					return false;	
				};
				if(_this_.citySelect.attr("issaved")=="yes"){
					arr.push(_this_.getSelectedText(_this_.citySelect));
				}else{
					_this_.tips(_this_.citySelect,"没有选择市！",false);
					return false;	
				};
				if(_this_.countySelect.attr("issaved")=="yes"){
					arr.push(_this_.getSelectedText(_this_.countySelect));
				}else{
					_this_.tips(_this_.countySelect,"没有选区县！",false);
					return false;	
				};
				
				if(_this_.detialInput.attr("issaved")=="yes"){
					arr.push(_this_.detialInput.val());
				}else{
					_this_.tips(_this_.detialInput,"详细地址不能为空！",false);
					return false;	
				};
				/**********邮编**********/
				if(_this_.userPost.attr("issaved")=="yes"){
					arr.push(_this_.userPost.val());
				}else{
					_this_.tips(_this_.userPost,"邮政编码不对！",false);
					return false;	
				};
				
				if(_this_.userPhoneInput.attr("issaved")=="yes"){
					arr.push(_this_.userPhoneInput.val());
				}else{
					_this_.tips(_this_.userPhoneInput,"手机号有错误！",false);
					return false;	
				};
				arr.push(_this_.userEmail.val());
				if(arr.length==8){
					_this_.setUpdateTo(arr);
					$(this).text("[修改]").attr("isModState","no");
					//显示修改状态
					_this_.closeModBox();
					_this_.sureAddressBtn.hide();
					
				};
			}; 
		});
		//保存编辑框
		this.editAreaBox=$(".write-address",this.shoujianrenBox);
	
		//获取表单元素
		this.userNameInput=$("#mod-user-name",this.shoujianrenBox);	
		this.provinceSelect=$("#province",this.shoujianrenBox);	
		this.citySelect=$("#city",this.shoujianrenBox);	
		this.countySelect=$("#county",this.shoujianrenBox);
		this.detialInput=$("#mod-detial-address",this.shoujianrenBox);
		/*********邮编**********/
		this.userPost=$("#mod-user-post",this.shoujianrenBox);
		this.userPhoneInput=$("#mod-user-phone",this.shoujianrenBox);
		this.userEmail=$("#mod-user-email",this.shoujianrenBox);
		//统一获取编辑元素
		this.allEditList=$(".all-edit-area",this.shoujianrenBox);
		//保存确认更改按钮
		this.submitAddressBtn=$(".submit-new-address",this.shoujianrenBox);
		this.submitAddressBtn.click(function(){
			//防止重复点击
			if(!$(this).data("isSubmit")){
				_this_.updateAddress();
			};
		});

		//保存span.yet-write
		this.yetWriteSpan=$(".yet-write",this.shoujianrenBox);
		//如果是没有默认地址
		var addressDefV=this.defaultAddress.attr("data-address-id");
		if(Number(addressDefV)==0){
			//dingwei
			this.isFirst = true;
			this.modCloseBtn.click();
			this.changeAddressListSelect(this.addressListBox.find("input").prop("checked",true));
		};
	};
	ShouJianRen.prototype={
		//更新地址
		updateAddress:function(){
			var arr=[];
			if(this.userNameInput.attr("issaved")=="yes"){
				arr.push(this.userNameInput.val());
			}else{
				this.tips(this.userNameInput,"用户名不对！",false);
				return false;
			};
			if(this.provinceSelect.attr("issaved")=="yes"){
				arr.push(this.getSelectedText(this.provinceSelect));
			}else{
				this.tips(this.provinceSelect,"没有选择省份！",false);
				return false;	
			};
			if(this.citySelect.attr("issaved")=="yes"){
				arr.push(this.getSelectedText(this.citySelect));
			}else{
				this.tips(this.citySelect,"没有选择市！",false);
				return false;	
			};
			if(this.countySelect.attr("issaved")=="yes"){
				arr.push(this.getSelectedText(this.countySelect));
			}else{
				this.tips(this.countySelect,"没有选区县！",false);
				return false;	
			};
			
			if(this.detialInput.attr("issaved")=="yes"){
				arr.push(this.detialInput.val());
			
			}else{
				this.tips(this.detialInput,"详细地址不能为空！",false);
				return false;	
			};
			/**********邮编**********/
			if(this.userPost.attr("issaved")=="yes"){
				arr.push(this.userPost.val());
			}else{
				this.tips(this.userPost,"邮政编码不对！",false);
				return false;	
			};
			
			if(this.userPhoneInput.attr("issaved")=="yes"){
				arr.push(this.userPhoneInput.val());
			
			}else{
				this.tips(this.userPhoneInput,"手机号有错误！",false);
				return false;	
			};
			arr.push(this.userEmail.val());
			if(arr.length==8){
				this.setUpdateTo(arr);
				this.modCloseBtn.click();
				return true;
			};
		},
		setUpdateTo:function(addressArr){
			var _this=this;
			var selectedID=this.addressListBox.find("input:checked").val();
			//防止重复点击
//			this.submitAddressBtn.text("数据提交中....").data("isSubmit",true);
			/*更改防止没有电子邮件时出现的逗号*/
			var lastStr=addressArr[7]!=""?","+addressArr[7]:"";
//			if(selectedID!="addNewAddress"){
					//<strong>杨永,</strong>江苏,宿迁市,沭阳县,经济开发区A#82,18911082350,sujie@126.com
//					this.addressListBox.find("span[data-address-id="+selectedID+"]").html("<strong>"+addressArr[0]+",</strong>"+addressArr[1]+","+addressArr[2]+","+addressArr[3]+","+addressArr[4]+","+addressArr[5]+","+addressArr[6]+lastStr);
					$("#sureAddress").html("<strong>"+addressArr[0]+",</strong>"+addressArr[1]+","+addressArr[2]+","+addressArr[3]+","+addressArr[4]+","+addressArr[5]+","+addressArr[6]+lastStr);
					$("#J_ValidateEdit").hide();
					//					this.defaultAddress.text(addressArr.join(","));

					/*					$.post("/consignee.do?",{address:addressArr.join(","),id:selectedID},function(ret){
						//防止重复点击
						_this.submitAddressBtn.data("isSubmit",false).text("确认收货地址");
						_this.modCloseBtn.click();
					});		
*/			
//					}else{
//				var li=$("<li class='selected'/>");
//				$.post("/consignee.do?",{address:addressArr.join(",")},function(ret){
//					/*如果返回的地址是没有邮件的。去掉最后一个逗号*/
//					li.html(ret);
//					_this.addressListBox.children().last().before(li);
//					_this.defaultAddress.text(addressArr.join(",")).attr("data-address-id",_this.addressListBox.find("input:checked").val());
//					//防止重复点击
//					_this.submitAddressBtn.data("isSubmit",false).text("确认收货地址");
//					_this.modCloseBtn.click();
//				})
//			};
//			
			
		},
		tips:function(thisObj,text,isOk){
			var tipsNode=$(thisObj).parent().find(".validate-tips");
			var tipsText=$("span",tipsNode)
			if(isOk){
				tipsNode.removeClass("validate-tips-error").show();
				tipsText.text(text);
			}else{
				tipsNode.addClass("validate-tips-error").show();
				tipsText.text(text);
			};
		},
		getSelectedText:function(selectNode){
			return $(selectNode).find(":selected").text();
		},
		//删除地址
		delAddress:function(thisObj,addressId){
				var _this=this;
				var addressID=$(thisObj).attr("data-address-id");
				var liNode=$(thisObj).parent().parent();
				//先移除节点
				liNode.fadeOut(function(){
					/**
					 * 如果删除节点不是最后一个就选中下一个，如果是最后一个并且有前一个就选中前一个
					 */
					if(liNode.next().find("input").val()!="addNewAddress"){
						liNode.next().find("input").click();
					}else if(liNode.siblings().length>0){
						liNode.prev().find("input").click();
					};
					liNode.remove();
					$.post("/consignee.do?",{id:addressID},function(ret){
						_this.hideEditBox();
					});	
				});
		},
		//设置编辑元素是否可以保存提交
		setEditSaveState:function(isSaved){
			if(isSaved){
				this.allEditList.attr("issaved","yes");
			}else{
				this.allEditList.attr("issaved","no");
			};
		},
		//获取当前编辑的地址内容
		getCurrentAddressText:function(thisObj){
			var text=$(thisObj).parent().prev().text();
			var addressArr=text.split(",");
			//alert(addressArr);
			//数据获取到后，初始化到输入框里
			this.initInputs(addressArr);
		},
		//根据地址ID初始化编辑框内容
		initInputs:function(addressArr){
			this.userNameInput.val(addressArr[0]);
			this.detialInput.val(addressArr[4]);
			this.userPost.val(addressArr[5]);
			this.userPhoneInput.val(addressArr[6]);
			/**********邮编***************/
			this.userEmail.val(addressArr[7]);
			this.yetWriteSpan.text(addressArr[1]+","+addressArr[2]+","+addressArr[3]);
			//初始化清空编辑
			this.emptyAllEdit();
			this.ajaxAddress([addressArr[1],addressArr[2],addressArr[3]]);
			//然后请求对应数据
		},
		ajaxAddress:function(addressObj){
			var _this=this;
			//如果传入了省市区就添加对应的数据到下拉选择框,注意:省份要中国地区所以数据
			if(addressObj){
				$.getJSON("/region.do?callback=?",{name:addressObj[0]+","+addressObj[1]},function(result){
						//添加所以省份
						_this.addAllProvinceOptions(result,addressObj[0]);
						//数据成功，添加到选项中
						_this.addCityAndCountryOptions(result,addressObj[1],addressObj[2]);
				});
			}else{
				//直接返回所以省份
				$.getJSON("/region.do?callback=?",function(result){
						_this.addAllProvinceOptions(result);
				});
			};
		},
		//添加所以省份
		addAllProvinceOptions:function(result,provinceName){
			var _this=this;
			/**
			*result={
						province:[],
						city:[],
						country:[]
						}
			
			*/
			//alert(provinceName);
			$(result.province).each(function(index, element) {
				if(element.name==provinceName){
						_this.provinceSelect.append("<option value="+element.id+" selected>"+element.name+"</option>");
				}else{
						_this.provinceSelect.append("<option value="+element.id+">"+element.name+"</option>");
				};
            });
		},
		//添加市县
		addCityAndCountryOptions:function(result,cityName,countName){
			var _this=this;
			/**
			*result={
						city:[],
						country:[]
						}
			
			*/
			//添加市
			$(result.city).each(function(index, element) {
				if(element.name==cityName){
						_this.citySelect.append("<option value="+element.id+" selected>"+element.name+"</option>");
				}else{
						_this.citySelect.append("<option value="+element.id+">"+element.name+"</option>");
				};

            });
			//添加区县
			$(result.country).each(function(index, element) {
				if(element.name==countName){
					_this.countySelect.append("<option value="+element.id+" selected>"+element.name+"</option>");
				}else{
					_this.countySelect.append("<option value="+element.id+">"+element.name+"</option>");
				};
            });
		},
		//清空所有编辑框
		emptyAllEdit:function(isEmptyAll){
			if(isEmptyAll){
				this.allEditList.val("");
			};
			this.provinceSelect.empty().append("<option value='0'>--选择省份--</option>");
			this.citySelect.empty().append("<option value='0'>--选择市--</option>");
			this.countySelect.empty().append("<option value='0'>--选择区县--</option>");
		},
		//显示编辑框
		showEditBox:function(){
			this.defaultAddress.hide();
			this.editAreaBox.show();
		},
		hideEditBox:function(){
			this.editAreaBox.hide();
		},
		//显示修改状态框
		showModBox:function(){
			this.shoujianrenBox.addClass("colunm-box-modify");
			//隐藏默认的地址
			this.defaultAddress.hide();
			//显示所有地址列表
			this.addressListBox.show();
			//匹配到对应的修改地址
			this.matchAddressNum();

		},
		//关闭修改状态
		closeModBox:function(){
			this.shoujianrenBox.removeClass("colunm-box-modify");
			//隐藏默认的地址
			this.defaultAddress.show();
			//显示所有地址列表
			this.addressListBox.hide();
			this.editAreaBox.hide();
		},
		//匹配默认地址和对应所以地址中的对应
		matchAddressNum:function(){
			var addressId=Number(this.defaultAddress.attr("data-address-id"));
			//设置对应修改地址
			this.addressListBox.find("input[value="+addressId+"]").click();/*.parent().next().next().find(".modify-btn").click();*/
			/****************/
			this.sureAddressBtn.show();
		},
		//切换地址选择
		changeAddressListSelect:function(thisRadio){ 
			//如果不是添加新地址，就单纯的切换样式，否则执行添加新地址
			if($(thisRadio).val()!="addNewAddress"){
				//切换地址状态
				$(thisRadio).parent().parent().addClass("selected").siblings().removeClass("selected");
				//设置对应的地址到默认项
				this.setAddressToDef(thisRadio);
				//隐藏编辑框
				this.hideEditBox();
				/****************/
				this.sureAddressBtn.show();
			}else{
				//切换地址状态
				$(thisRadio).parent().parent().addClass("selected").siblings().removeClass("selected");
				//如果是添加新地址，就清空输入框
				this.emptyAllEdit(true);
				this.setEditSaveState(false);
				this.yetWriteSpan.text("");
				//如果是使用新地址,就获取所有省份
				this.ajaxAddress();
				this.showEditBox();
				this.shoujianrenBox.find(".validate-tips").hide();
				this.sureAddressBtn.hide();
			};
		},
		//设置新地址到默认选中项
		setAddressToDef:function(thisRadio){
			//拿到当前地址
			var curAddress=$(thisRadio).parent().next().text();
			//设置到默认地址里
			this.defaultAddress.text(curAddress).attr("data-address-id",$(thisRadio).val());
		}
	};
	//创建收件人
	var J_ShouJianRen=new ShouJianRen($("#J_ShouJianRen"));

	//单独的验证框
	function ValidateEdit(validateBox){
			var _this_=this;
			this.validateArea=validateBox;
			//获取表单元素
			this.userNameInput=$("#mod-user-name",this.validateArea);	
			this.provinceSelect=$("#province",this.validateArea);	
			this.citySelect=$("#city",this.validateArea);	
			this.countySelect=$("#county",this.validateArea);
			this.detialInput=$("#mod-detial-address",this.validateArea);
			/*********邮编**********/
			this.userPost=$("#mod-user-post",this.shoujianrenBox);
			this.userPhoneInput=$("#mod-user-phone",this.validateArea);
			this.userEmail=$("#mod-user-email",this.validateArea);
			//统一获取编辑元素
			this.allEditList=$(".all-edit-area",this.shoujianrenBox);
	
			//保存span.yet-write
			this.yetWriteSpan=$(".yet-write",this.shoujianrenBox);
			

			this.provinceSelect.change(function(){
				if(this.value==0){
					_this_.citySelect.empty().append("<option value=0>--选择市--</option>");
					_this_.countySelect.empty().append("<option value=0>--选择区县--</option>");
					$(this).attr("issaved","no");
					_this_.citySelect.attr("issaved","no");
					_this_.countySelect.attr("issaved","no");
					_this_.tips(this,"没有选择省份！",false);
				}else{
					_this_.citySelect.empty();
					_this_.countySelect.empty();
					//加载对应的市
					_this_.getAddress(_this_.getSelectedText(this),"");
					$(this).attr("issaved","yes");
					_this_.tips(this,"省份正确！",true);
					_this_.citySelect.attr("issaved","no");
					_this_.countySelect.attr("issaved","no");
					_this_.setYet();
				};
			});
			this.citySelect.change(function(){
				//加载对应的区县
				if(this.value!=0){
					_this_.getAddress(_this_.getSelectedText(_this_.provinceSelect),_this_.getSelectedText(this));
					_this_.setYet();
					$(this).attr("issaved","yes");
					_this_.countySelect.attr("issaved","no");
					_this_.tips(this,"城市选择正确！",true);
				}else{
					_this_.tips(this,"没有选择市！",false);
					$(this).attr("issaved","no");
				};
			});
			this.countySelect.change(function(){
				if(this.value==0){
					$(this).attr("issaved","no");
					_this_.tips(this,"没有选择区县！",false);
				}else{
					_this_.setYet();
					$(this).attr("issaved","yes");
					_this_.tips(this,"地区选择正确！",true);
				};
			});
			
			//验证用户名
			this.userNameInput.keyup(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vUserName(v,_this);
				},500);
			}).blur(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vUserName(v,_this);
				},500);
			});
			
			//验证详细地址
			this.detialInput.keyup(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vDetialAddress(v,_this);
				},500);
			}).blur(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vDetialAddress(v,_this);
				},500);	
			});
			//验证邮编
			this.userPost.keyup(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vPost(v,_this);
				},500);
			}).blur(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vPost(v,_this);
				},500);	
			});
			
			//验证手机
			this.userPhoneInput.keyup(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vPhone(v,_this);
				},500);
			}).blur(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vPhone(v,_this);
				},500);	
			});
	};
	
	ValidateEdit.prototype={
		//验证邮编
		vPost:function(v,thisObj){
			if(v.isPostcode()){
				$(thisObj).attr("issaved","yes");
				this.tips(thisObj,"正确！",true);
			}else{
				$(thisObj).attr("issaved","no");
				this.tips(thisObj,"邮编不对！",false);
			};	
		
		},
		//验证手机
		vPhone:function(v,thisObj){

			if(v.isMobile()){
				$(thisObj).attr("issaved","yes");
				this.tips(thisObj,"正确！",true);
			}else{
				$(thisObj).attr("issaved","no");
				this.tips(thisObj,"手机格式不对！",false);
			};		
		
		},
		//验证详细地主
		vDetialAddress:function(v,thisObj){
			var v=$.trim(v);
			if(v!=""){
				$(thisObj).attr("issaved","yes");
				this.tips(thisObj,"正确！",true);
			
			}else{
				$(thisObj).attr("issaved","no");
				this.tips(thisObj,"没有填写详细地址！",false);
			};
		},
		//验证用户名
		vUserName:function(v,thisObj){

			if(v.isUserName()){
				$(thisObj).attr("issaved","yes");
				this.tips(thisObj,"用户名正确！",true);
			}else{
				
				$(thisObj).attr("issaved","no");
				this.tips(thisObj,"用户名输入有误！",false);
			};
		},
		tips:function(thisObj,text,isOk){
			// validate-tips-error
			var tipsNode=$(thisObj).parent().find(".validate-tips");
			var tipsText=$("span",tipsNode)
			if(isOk){
				tipsNode.removeClass("validate-tips-error").show();
				tipsText.text(text);
			}else{
				tipsNode.addClass("validate-tips-error").show();
				tipsText.text(text);
			};
		
		},
		setYet:function(){
			
			if(this.provinceSelect.val()!=0){
				this.yetWriteSpan.text(this.getSelectedText(this.provinceSelect));
			};
			if(this.citySelect.val()!=0){
				this.yetWriteSpan.text(this.getSelectedText(this.provinceSelect)+","+this.getSelectedText(this.citySelect)+",");
			};
			if(this.countySelect.val()!=0){
				this.yetWriteSpan.text(this.getSelectedText(this.provinceSelect)+","+this.getSelectedText(this.citySelect)+","+this.getSelectedText(this.countySelect));
			};
			
		},
		getSelectedText:function(selectNode){
			return $(selectNode).find(":selected").text();
		},
		getAddress:function(cityName,conutName){
				var _this=this;
				$.getJSON("/region.do?callback=?",{name:cityName+","+conutName},function(result){
					if(conutName==""){
						_this.citySelect.empty().append("<option value=0>--选择市--</option>");
						_this.countySelect.empty().append("<option value=0>--选择区县--</option>");
						$(result.city).each(function(i,o){
							_this.citySelect.append("<option value="+o.id+">"+o.name+"</option>");
						});
					}else{
						_this.countySelect.empty().append("<option value=0>--选择区县--</option>");
						$(result.country).each(function(i,o){
							_this.countySelect.append("<option value="+o.id+">"+o.name+"</option>");
						});
					};	
				});
		}
	
	
	};
	
	var ValidateEdit=new ValidateEdit($("#J_ValidateEdit"));

	/*************************配送方式************************************/
	
	function ShippingMethod(obj){
		var _this_=this;
		//保存配送方式区域
		this.shippingBox=obj;
		//保存修改关闭按钮
		this.modAndCloseBtn=$(".colunm-hd span",obj);
		//保存listBox
		this.expressListBox=$("#express-list",obj);
		//获取一下快递标识区域
		this.expressArea=$("#sureAddress");
		this.modAndCloseBtn.click(function(){
			//如果不是修改状态
			if($(this).attr("isModState")!="yes"){
				$(this).text("[关闭]").attr("isModState","yes");
				var addressValue=_this_.expressArea.attr("data-address-id");
				
				$.get("/cartCenter/methods.do",{cid:addressValue},function(ret){
					
					_this_.expressListBox.html(ret);
					//显示修改状态
					_this_.showModBox();
				})
				
	
			}else if($(this).attr("isModState")!="no"){
				$(this).text("[修改]").attr("isModState","no");
				//显示修改状态
				_this_.closeModBox();
			};
		
		});
	
		//保存默认的p
		this.defExpress=$("#defaultExpressName",obj);
		this.defShipping=$("#defaultShippingMethod",obj);
		
		//保存快递列表项
		this.expressListBox=$("#express-list",obj);
		this.expressListBox.click(function(e){
			if(e.target.tagName=="INPUT"){
				_this_.setExpress(e.target);
			};
		});

		//保存支付列表
		this.shippingListBox=$("#shipping-method-list",obj);
		this.shippingListRadio=$("#shipping-method-list input",obj);
		this.shippingListRadio.click(function(){
			_this_.setShipping(this);

		});
		//保存确认按钮
		this.sureBtn=$(".sure-express-btn",obj);
		this.sureBtn.click(function(){
			_this_.closeModBox();
			_this_.modAndCloseBtn.attr("isModState","no").text("[修改]");
			/*------打开支付方式--------*/
			if($("#J_PayMethod span").attr("isModState")!="yes"){
				$("#J_PayMethod span").click();
			};
		});
	};
	ShippingMethod.prototype={
		
		setShipping:function(thisObj){
			$(thisObj).parent().addClass("selected").siblings().removeClass("selected");
			this.defShipping.attr("data-id",$(thisObj).val()).text($(thisObj).next().text());
		},
		setExpress:function(thisObj){
			$(thisObj).parent().addClass("selected").siblings().removeClass("selected");
			this.defExpress.attr({
								"data-id":$(thisObj).val(),
								"data-deliverydepartmentid":$(thisObj).attr("data-deliverydepartmentid")
								}).text($(thisObj).next().text());
		},
		showModBox:function(){
			this.shippingBox.addClass("colunm-box-modify");
			//当显示的时候选择上默认的
			var expressID=this.defExpress.attr("data-id");
			var shippingID=this.defShipping.attr("data-id");
			//找到当前选中的快递项
			this.expressListBox.find("input[value="+expressID+"]").prop("checked",true);
			this.setExpress(this.expressListBox.find("input[value="+expressID+"]"));
			this.shippingListBox.find("input[value="+shippingID+"]").click();
			
		},
		closeModBox:function(){
			this.shippingBox.removeClass("colunm-box-modify");
		}
	
	};
	
	var shippingMethod=new ShippingMethod($("#J_ShippingMethod"));
	
	
	
	/*************************支付方式************************************/
	
	function PayMethod(obj){
		var _this_=this;
		//保存配送方式区域
		this.payBox=obj;
		//保存修改关闭按钮
		this.modAndCloseBtn=$(".colunm-hd span",obj);
		//获取银行转账按钮payFun-2
		this.yinhangBtn=$("input",obj);
		//获取提示信息
		this.tipsBox=$(".state-tips",obj);
		this.yinhangBtn.click(function(){
			if($(this).attr("id")=="payFun-2"){
				_this_.tipsBox.show();
			}else{
				_this_.tipsBox.hide();
			};
		});
		this.yinhangBtn=$(".state-tips",obj);
		
		this.modAndCloseBtn.click(function(){
			//如果不是修改状态
			if($(this).attr("isModState")!="yes"){
				$(this).text("[关闭]").attr("isModState","yes");
				//显示修改状态
				_this_.showModBox();
				
			}else if($(this).attr("isModState")!="no"){
				$(this).text("[修改]").attr("isModState","no");
				//显示修改状态
				_this_.closeModBox();
			};
		
		});
		//获取默认的支付方式
		this.defPay=$("#defaultPayMethod",obj);
		//获取列表框
		this.payMethodListBox=$("#pay-main-mod",obj);
		this.payMethodList=$("input",this.payMethodListBox);
		
		this.payMethodList.click(function(){
			_this_.setPayMethod(this);
		});
		//保存确认按钮
		this.sureBtn=$(".sure-express-btn",obj);
		this.sureBtn.click(function(){
			_this_.closeModBox();
			_this_.modAndCloseBtn.attr("isModState","no").text("[修改]");
		});
	
	};
	PayMethod.prototype={
		setPayMethod:function(thisObj){
			$(thisObj).parent().addClass("selected").siblings().removeClass("selected");
			this.defPay.text($(thisObj).next().text()).attr({
															"data-id":$(thisObj).val(),
															"data-p2mid":$(thisObj).attr("data-p2mid")
															});
		},
		showModBox:function(){
			this.payBox.addClass("colunm-box-modify");
			this.payMethodListBox.find("input[value="+this.defPay.attr("data-id")+"]").click();
		},
		closeModBox:function(){
			this.payBox.removeClass("colunm-box-modify");
		}
	
	};
	
	var payMethod=new PayMethod($("#J_PayMethod"));
	
/**************优惠券和统计******************/
	
	function CouponTotal(main){
		var _this_=this;
		//保存优惠券展开关闭按钮
		this.closeOrOpenBtn=$("#use-coupon",main);
		//保存优惠券选项卡
		this.conuponTabMain=$("#tab-box",main);
		this.closeOrOpenBtn.click(function(){
			if($(this).data("isOpen")){
				$(this).text("使用优惠券+");
				$(this).data("isOpen",false);
				_this_.conuponTabMain.toggle();
			}else{
				$(this).text("使用优惠券-");
				$(this).data("isOpen",true);
				_this_.conuponTabMain.toggle();
			};
		});
		//保存tabs
		this.tabMenus=$(".tab-change li",main);
		//保存tab对应内容
		this.tabContents=$(".tab-content .tab-content-item",main);
		this.tabMenus.click(function(){
			$(this).addClass("selected").siblings().removeClass("selected");
			_this_.tabContents.eq($(this).index()).addClass("tab-content-item-show").siblings().removeClass("tab-content-item-show");
		});
		//保存优惠券使用按钮
		this.conuponRadios=$(".tab-content input",main);/*.prop("checked",false)*/;
		this.totalMoney=0;
		this.totalNum=0;
		this.conuponRadios.each(function(){
			if(this.checked){
				_this_.totalNum++;
				_this_.totalMoney+=Number(this.value);
			};
		});
		//保存优惠券使用状况
		this.conupUseDetialSize=$("#use-coupon-detial span").eq(0).text(this.totalNum);
		this.conupUseDetialMoney=$("#use-coupon-detial span").eq(1).text("￥"+this.totalMoney);
		//获取统计区域的优惠券使用总金额
		this.couponTotalMoney=$("#coupon-total-money",main);
		//获取e钱包按钮
		this.ePayRadio=$("#e-pay",main)/*.prop("checked",false)*/;
		//保存下应付总金额
		this.totalPay=$("#total-pay strong",main);
		//保存商品总金额，保持不变
		this.productsMoney=$("#products-total-money",main).text();
		this.productsMoney=Number(this.productsMoney);
		//选中的累加
		this.selectedConupArr=null;
		this.conuponRadios.click(function(){
				_this_.selectedConupArr=[];
				_this_.conuponRadios.each(function(){
					if(this.checked){
						//_this_.selectedConupArr.push({value:Number(this.value),key:$(this).attr("data-id")});
						_this_.selectedConupArr.push($(this).attr("data-id"));
					};
				});
				_this_.conupUseDetialSize.text(_this_.selectedConupArr.length);
				
				//_this_.conupUseDetialMoney.text("￥"+_this_.calculateUse(_this_.selectedConupArr));
				
				//_this_.couponTotalMoney.text("￥"+_this_.calculateUse(_this_.selectedConupArr));
				
				_this_.successMod(_this_.selectedConupArr.join(","),this);
				//如果e钱包勾选则
				//var ePayValue=_this_.ePayRadio.val();
				//if(_this_.ePayRadio.get(0).checked){
				//	_this_.setPayMoney(_this_.productsMoney-_this_.calculateUse(_this_.selectedConupArr)-Number(ePayValue));
				//}else{
				//	_this_.setPayMoney(_this_.productsMoney-_this_.calculateUse(_this_.selectedConupArr));
				//};	
		});
		
		this.ePayRadio.click(function(){
			/*var v=Number(this.value);
			var payV=_this_.totalPay.text();
			payV=Number(payV);
			if(this.checked){
				_this_.totalPay.text(payV-v);
			}else{
				_this_.totalPay.text(payV+v);
			};*/
			_this_.modEPay(this);
		});
		
		//保存页面提交按钮wjykan
		this.pageSubmitBtn=$("#go-pay-btn",main);
		//保存页面提交元素
		this.savePageSubmitElement();
		//用来存储优惠券ID
		this.saveCouponArr=null;
		this.pageSubmitBtn.click(function(){
			/********************重点开发对象 ，需要保存页面上的数据***************************/
			var arr=[];
			if(J_ShouJianRen.userNameInput.attr("issaved")=="yes"){
				arr.push(J_ShouJianRen.userNameInput.val());
			}else{
				J_ShouJianRen.tips(J_ShouJianRen.userNameInput,"用户名不对！",false);
				return false;
			};
			if(J_ShouJianRen.provinceSelect.attr("issaved")=="yes"){
				arr.push(J_ShouJianRen.getSelectedText(J_ShouJianRen.provinceSelect));
			}else{
				J_ShouJianRen.tips(J_ShouJianRen.provinceSelect,"没有选择省份！",false);
				return false;	
			};
			if(J_ShouJianRen.citySelect.attr("issaved")=="yes"){
				arr.push(J_ShouJianRen.getSelectedText(J_ShouJianRen.citySelect));
			}else{
				J_ShouJianRen.tips(J_ShouJianRen.citySelect,"没有选择市！",false);
				return false;	
			};
			if(J_ShouJianRen.countySelect.attr("issaved")=="yes"){
				arr.push(J_ShouJianRen.getSelectedText(J_ShouJianRen.countySelect));
			}else{
				J_ShouJianRen.tips(J_ShouJianRen.countySelect,"没有选区县！",false);
				return false;	
			};
			
			if(J_ShouJianRen.detialInput.attr("issaved")=="yes"){
				arr.push(J_ShouJianRen.detialInput.val());
			}else{
				J_ShouJianRen.tips(J_ShouJianRen.detialInput,"详细地址不能为空！",false);
				return false;	
			};
			/**********邮编**********/
			if(J_ShouJianRen.userPost.attr("issaved")=="yes"){
				arr.push(J_ShouJianRen.userPost.val());
			}else{
				J_ShouJianRen.tips(J_ShouJianRen.userPost,"邮政编码不对！",false);
				return false;	
			};
			
			if(J_ShouJianRen.userPhoneInput.attr("issaved")=="yes"){
				arr.push(J_ShouJianRen.userPhoneInput.val());
			}else{
				this.tips(J_ShouJianRen.userPhoneInput,"手机号有错误！",false);
				return false;	
			};
			arr.push(J_ShouJianRen.userEmail.val());
			if(arr.length==8){
				/*****拿到的数据*www******/
				$(this).text("正在提交...");
				//ie6兼容
				if(/MSIE 6.0/g.test(navigator.userAgent)){
					var params=_this_.getAllSubData(this.saveCouponArr);
					var  url="/AddOrder.do";
					var isFirst = true;
					for(var name in params){
						if(isFirst){
							url=url+"?";
							isFirst=false;
						}else{
							url=url+"&";
						}
						url=url+name+"="+params[name];
					}
					window.location.href = url;
				}else{
					_this_.createForm().get(0).submit();
				};
			};
		});
		//保存表单
		this.orderAllSubmit=$("#orderAllSubmit",main);
	};
	CouponTotal.prototype={
		//修改e钱包wjyGai 
		modEPay:function(thisObj){
			var useEmoneyPay=0;
			if(thisObj.checked){
				useEmoneyPay=1;
			}
			$.post("/useEmoneyPay.do",{useEmoneyPay:useEmoneyPay},function(json){
				
				$("#total-pay strong").html(json.totalNeedPayPrice);
				$("#e-have").html("￥"+json.totalEMoney);
				$("#e-payLe").html("￥"+json.useEMoney);
			},"json");
		},
		//后台修改
		successMod:function(str,thisObj){
				$.get("/checkCoupons.do?rand="+Math.random(),{discountIds:str},function(json){
					if(json.state=="error"){
						var d=new Dialog({
							  type:"alert",
							  text:"提示框",
							  tipsText:"购物券组合不能使用",
							  buttonSureText:"知道了", 
							  buttonCancelText:"关闭", 
							  callBack:function(){        
									thisObj.checked=false;
							  },
							  mask:0.3,
							  isDrag:true             
						});
						var couponsArea=$($("#use-coupon-detial span").get(0));
						couponsArea.html(parseInt(couponsArea.html())-1);
					}else{
						$("#total-pay").html("￥<strong>"+json.totalNeedPayPrice+"</stropn>");
						$("#coupon-total-money").html("￥"+json.totalDiscountPrice);
						$("#useCouponPrice").text("￥"+json.couponPrice);
						
						if(json.totalEmoney!==undefined){// json.totalEmoney
							$("#e-have").html(json.totalEmoney);
						};
						
					}
				},"json");
			
		},
		//创建表单
		createForm:function(){
			var formObj=$("<form action='/order/submitPointOrder.do' style='display:none;' method='post' />");
			var params=this.getAllSubData(this.saveCouponArr);
			for(var i in params){
				formObj.append("<input type='hidden' name="+i+" value="+params[i]+">");
			};
			$("body").append(formObj);
			return formObj;
		},
		//获取页面中所以要执行的数据
		getAllSubData:function(couponArr){
			var buyerName = $('#mod-user-name').val();
			var sendArea = $('#county').val();
			var address = $('#mod-detial-address').val();
			var postCode = $('#mod-user-post').val();
			var phone = $('#mod-user-phone').val();
			var email = $('#mod-user-email').val();
			var iObjectID = $('#iObjID').val();
			var formToken = $('#formToken').val();
			var postData = {
					buyerName:buyerName,
					sendArea:sendArea,
					address:address,
					postCode:postCode,
					phone:phone,
					email:email,
					iObjectID:iObjectID,
					formToken:formToken
			};
			console.log(postData);
			return postData;
		},
		//保存一下页面最终要提交的元素
		savePageSubmitElement:function(){
			//1,收件人地址
			this.addressSub=$("#sureAddress");
			//2,配送快递
			this.expressSub=$("#defaultExpressName");
			//3,保存配送日期
			this.expressDateSub=$("#defaultShippingMethod");
			//4,保存支付方式
			this.payMethodSub=$("#defaultPayMethod");
			//5,保存e钱包
			this.ePaySub=$("#e-pay");
			//6,应付金额
			this.payMoney=$("#total-pay strong");
		},
		//设置应付金额
		setPayMoney:function(value){
			this.totalPay.text(value);
		},
		//计算节省的钱
		calculateUse:function(arr){
			var loop=0;
			$(arr).each(function(index, element) {
				loop+=element.value;
            });
			return loop;
		}
	};
	
	var couponTotal=new CouponTotal($("#product-list-main"));

	function YunFei(conf){
		this.url=conf.url;
		this.idName=conf.idName;
		this.dIdName=conf.dIdName;
	}
	
	YunFei.prototype={
		update:function(){
			var id=$("#sureAddress").attr("data-address-id");
			var dId=$("#defaultExpressName").attr("data-deliverydepartmentid");
			this.send(this.url,id,dId);
		},
		setTotalNeedPrice:function(price){
			$("#total-pay strong").html(price);
		},
		setTotalYunfei:function(price){
			$("#total-yunFei").html("￥"+price);
		},
		send:function(url,id,dId){
			var _this=this;
			var params={};
			params[_this.idName]=id;
			params[_this.dIdName]=dId;
			
			var time = new Date();
			
			$.post(url+"?time="+time.getTime(),params,function(ret){
				var shopCart=ret.shoppingCart;
				var eMoney=ret.emoneyBlance;
				_this.setTotalNeedPrice(shopCart.totalNeedPayPrice);
				_this.setTotalYunfei(shopCart.totalDeliveryPrice);
				$("#e-have").html("￥"+eMoney);
			},"json");
		}
	}
	
	var yunFei=new YunFei({
		url:"/updateDeliverPrice.do",
		idName:"id",
		dIdName:"deliveryDepartmentId"
	});
	
});